package com.nstar.sinaweibo.model
{
	import com.nstar.base.util.StringUtils;
	import com.sina.microblog.MicroBlog;
	
	import flash.display.DisplayObject;
	import flash.display.Graphics;
	import flash.display.NativeWindow;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.filters.BitmapFilterQuality;
	import flash.filters.BlurFilter;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.system.Capabilities;
	import flash.text.TextField;
	
	import gs.TweenLite;
	import gs.easing.Elastic;
	
	import mx.containers.Canvas;
	import mx.controls.Text;
	import mx.controls.TextArea;
	import mx.core.Container;
	import mx.core.Window;
	import mx.core.mx_internal;
	import mx.formatters.DateFormatter;
	import mx.styles.StyleManager;  
	
	use namespace mx_internal; 		
	
	/**
	 * 微博基本工具类
	 * 
	 * 
	 */ 
	public class Utils
	{
		public static const APP_ID:String = "2913256261";//我的应用ID
		public static const APP_SECRET:String = "db9c75f5fdcf1ec661f1c648ef20a9d5";
		public static const REPLACE_CHAR:String = "[x]";
		public static const UNREAD_COLOR:uint = 0x80FF80;
		public static const LF:String = "\n";
		
		private static var microBlog:MicroBlog;
		
		//取得微博应用对象
		public static function getMicroBlog():MicroBlog
		{
			if(!microBlog){
				microBlog = new MicroBlog();
				microBlog.source = APP_ID;
			}
			return microBlog;
		}
		
		public static function formatDate(d:Date, fmt:String):String
		{
			var format:DateFormatter = new DateFormatter();
			format.formatString = fmt;
			return format.format(d);
		}
		
		public static function getDateString(d:Date):String
		{
			var dateString:String;
			var now:Date = new Date();
			var interval:Number = now.getFullYear() - d.getFullYear();
			if (interval != 0)
			{
				dateString = formatDate(d, "YYYY.MM.DD HH:NN");
			}
			else
			{
				interval = now.getMonth() - d.getMonth();
				if (interval != 0)
				{
					dateString = formatDate(d, "MM月DD日 HH:NN");
				}
				else
				{
					interval = now.getDate() - d.getDate();
					if (interval != 0)
					{
						dateString = formatDate(d, "MM月DD日 HH:NN");
					}
					else
					{
						interval = now.getHours() - d.getHours();
						if (interval != 0)
						{
							dateString = formatDate(d, "今天 HH:NN");
						}
						else
						{
							interval = now.getMinutes() - d.getMinutes();
							if (interval < 0)
							{
								dateString = formatDate(d, "今天 HH:NN");
							}
							else if (interval > 0)
							{
								dateString = interval + "分钟前";
							}
							else if (interval == 0)
							{
								dateString = "1分钟前";
							}
						}
					}
				}
			}
			return dateString;
		}
		
		public static function checkInput(t:String):Boolean
		{
//			if (cnLength(t) > 280)
			if (t.length > 140)
			{
				return false;
			}
			return true;
		}
		
		public static function countInput(t:String):int
		{
			//return int( (280 - cnLength(t)) / 2 );
			return 140 - t.length;
		}
		
		public static function cnLength(str:String):int
		{
			var n:int = str.replace(/[^\x00-\xff]/g, "xx").length;
			return n;
		}
		
		public static function trimStr(str:String):String
		{
			return str.replace(/(^\s*)|(\s*$)/g, '');
		}
		
		public static function replaceSpace(str:String):String
		{
			return str.replace(/[\s*]+/g, ' ');
		}
		
		public static function transformStr(str:String):String
		{
			str = str.replace(/&quot;/g, "\"");
			str = str.replace(/&amp;/g, "&");
			str = str.replace(/>/g, "&gt;");
			str = str.replace(/</g, "&lt;");
			return str;
		}
		
		public static function getStatusHtmlText(str:String):String
		{
			if(!str) return null;
			str = getSourceHtmlText(str);//先处理一下HTML标签
			str = replaceSpace(str);
			str = transformStr(str);
			var atRegx:RegExp = /@([A-Za-z0-9\u4e00-\u9fa5_-]+)/gi;
			var keywordRegx:RegExp = /(?<![color='])#([^#]+)#/gi;
			var shortUrlRegx:RegExp = /((http[s]?|ftp)?:\/\/(([\w-]+:)?[\w-]+@)?([\w-]+\.)+[\w-]+(:[\d]+)?(\/[\w-   .\/?%&=]*)?(#[\w,]+)?)/gi;
			str = str.replace(shortUrlRegx, "<font color='#005ED9'><a href='$1' target='_blank'>$1</a></font>");
//			str = str.replace(atRegx, "<font color='#005ED9'><a href='http://t.sina.com.cn/n/$1' target='_blank'>@$1</a></font>");
			str = str.replace(atRegx, "<font color='#005ED9'><a href='event:$1' target='_blank'>@$1</a></font>");
			str = str.replace(keywordRegx, "<font color='#005ED9'><a href='http://t.sina.com.cn/k/$1' target='_blank'>#$1#</a></font>");
			return str;
		}
		
		//处理文本中的HTML标签
		public static function getSourceHtmlText(str:String):String
		{
			if(!str) return null;
			
			var aRegx:RegExp = /<a[\s]+[^>]*?href[\s]?=[\s\"\']+(.*?)[\"\']+.*?>([^<]+|.*?)?<\/a>/gi;
			str = str.replace(aRegx, "$2");
			return str;
		}
		
		public static function createSourceHtmlText(str:String):String{
			return "<font color='#005ED9'>"+str+"</font>"
		}
		
		public static function createVerifiedHtmlText(str:String):String{
			return "<font color='#FF0000'>"+str+"</font>"
		}
		
		
		public static function trunckStr(str:String, length:int):String
		{
			if ( length <= str.length )
			{
				return str;
			}
			return str.slice(0, length);
		}
		
		//返回用户超级链接
		public static function getUserLink(userID:uint,userScreenName:String):String{
			return "<b><font color='#005ED9'><a href='http://t.sina.com.cn/" + userID + "' target='_blank'>"+ userScreenName + "</a></font></b>";
			//return "<b><font color='#8080FF'><a href='event:" + userScreenName + "' target='_blank'>"+ userScreenName + "</a></font></b>";
		}
		
		//设置弹出窗口的位置
		public static function resetWindowPos(app:NativeWindow,popWin:Window):String{
			var result:String = "left";
			var relx:Number = Capabilities.screenResolutionX;
			var rely:Number = Capabilities.screenResolutionY;
			if(app.x<popWin.width){
				popWin.nativeWindow.x = app.width+app.x;
				result = "right";
			}else{
				popWin.nativeWindow.x = app.x - popWin.width;
				result = "left";
			}
			
			if((rely-app.y)<popWin.height){
				popWin.nativeWindow.y = rely - popWin.height -10;
			}else{
				popWin.nativeWindow.y = app.y + 30;
			}	
			
			return result;		
		}
		
		//使窗口居中
		public static function centerWindow(win:NativeWindow):void{
			var relx:Number = Capabilities.screenResolutionX;
			var rely:Number = Capabilities.screenResolutionY;
			win.x = (relx-win.width)/2;
			win.y = (rely-win.height)/2;
		}
		
		//获取屏幕中央位置
		public static function getScreenCenter(win:Object):Point{
			var p:Point = new Point();
			var relx:Number = Capabilities.screenResolutionX;
			var rely:Number = Capabilities.screenResolutionY;
			p.x = (relx-win.width)/2;
			p.y = (rely-win.height)/2;
			return p;	
		}
		
		//获取屏幕大小
		public static function getScreenResolution():Point{
			return new Point(Capabilities.screenResolutionX,Capabilities.screenResolutionY);
		}
		
		//获取消息中的@列表
		public static function getAtList(str:String):Array{
			var atRegx:RegExp = /@([A-Za-z0-9\u4e00-\u9fa5]+)/gi;
			var ary:Array = str.match(atRegx);
			//去掉重复的
			var result:Array = new Array();
			for each(var str:String in ary){
				if(result.indexOf(str)==-1){
					result.push(str);
				}
			}
			return result;
		}
		
		//匹配表情列表
		public static function getFaceList(str:String):Array{
			var face:RegExp = /(\[[A-Za-z0-9\u4e00-\u9fa5]+)\]/gi;
			return str.match(face);
		}
		
		//获取文本输入框中当前光标相对于文本框左上角的位置
		public static function getCaretLocation(ta : TextArea) : Point {  
		    var tf : TextField = ta.getTextField() as TextField;  
		    var index : Number = tf.caretIndex;  
		    var x : Number, y : Number;  
		    var rect : Rectangle;  
		    if ('' == ta.text.charAt(index)) {  
		        if (0 == index) {  
		            // the TextArea is empty  
		            x = 2;  
		            y = 2;  
		        } else if ('\n' == ta.text.charAt(index - 1) || '\r' == ta.text.charAt(index - 1)) {  
		            // at the start of a new line, and also at the end of a the line  
		            // use lineHeight * lineIndex + yPadding as y  
		            x = 2;  
		            y = tf.getLineMetrics(0).height * (tf.getLineIndexOfChar(index - 1) + 1) + 2;  
		        } else {  
		            // at the end of a line  
		            // use the bounds of the charater to the left of caret, and add the width of it to x  
		            rect = tf.getCharBoundaries(index - 1);  
		            x = rect.x + rect.width;  
		            y = rect.y;  
		        }  
		    } else {  
		        if ('\n' == ta.text.charAt(index) || '\r' == ta.text.charAt(index)) {  
		            // at the start of a line, but not at the end of the line  
		            x = 2;  
		            y = tf.getLineMetrics(0).height * tf.getLineIndexOfChar(index) + 2;  
		        } else {  
		            // in middle of a line  
		            rect = tf.getCharBoundaries(index);  
		            x = rect.x;  
		            y = rect.y;  
		        }  
		    }  
		    return new Point(x, y);  
		}
		
		//获取文本在文本域中的位置
		public static function getCharPoint(ta:Text,text:String):Point{
			var tf : TextField = ta.getTextField() as TextField;  
		    var index : Number = ta.text.indexOf(text);
		    var x : Number, y : Number;  
		    var rect : Rectangle;  
		    if ('' == ta.text.charAt(index)) {  
		        if (0 == index) {  
		            // the TextArea is empty  
		            x = 2;  
		            y = 2;  
		        } else if ('\n' == ta.text.charAt(index - 1) || '\r' == ta.text.charAt(index - 1)) {  
		            // at the start of a new line, and also at the end of a the line  
		            // use lineHeight * lineIndex + yPadding as y  
		            x = 2;  
		            y = tf.getLineMetrics(0).height * (tf.getLineIndexOfChar(index - 1) + 1) + 2;  
		        } else {  
		            // at the end of a line  
		            // use the bounds of the charater to the left of caret, and add the width of it to x  
		            rect = tf.getCharBoundaries(index - 1);  
		            x = rect.x + rect.width;  
		            y = rect.y;  
		        }  
		    } else {  
		        if ('\n' == ta.text.charAt(index) || '\r' == ta.text.charAt(index)) {  
		            // at the start of a line, but not at the end of the line  
		            x = 2;  
		            y = tf.getLineMetrics(0).height * tf.getLineIndexOfChar(index) + 2;  
		        } else {  
		            // in middle of a line  
		            rect = tf.getCharBoundaries(index);  
		            x = rect.x;  
		            y = rect.y;  
		        }  
		    } 
		    
		    ta.text = ta.text.replace(text,REPLACE_CHAR);
		    ta.validateNow();
		    return new Point(x, y);  
		}
		
		//产生count个空格
		public static function whiteSpace(count:int):String{
			var result:String = "";
			for(var i:int = 0;i<count;i++){
				result += "&nbsp;";
			}
			return result;
		}		
		
		//绘制消息的分隔线
		public static function drawMsgBackSperator(cav:Canvas):void{
			var g:Graphics = cav.graphics;
			g.clear();
			g.lineStyle(1,0xFFFFFF);
			g.moveTo(0,cav.height-3);
			g.lineTo(cav.width,cav.height-3);
			g.lineStyle(1,0xC2E6FF);
			g.moveTo(0,cav.height-2);
			g.lineTo(cav.width,cav.height-2);
			g.lineStyle(1,0xFFFFFF);
			g.moveTo(0,cav.height-1);
			g.lineTo(cav.width,cav.height-1);
		}
		
		//解析用户头像URL
		private static function parseProfileImageUrl(profileImageUrl:String,size:int):String{
			var result:String = StringUtils.replace(profileImageUrl,"/50/","/"+size+"/");
			return result;
		}
		
		//取30*30大小的图片
		public static function getProfileImage30(profileImageUrl:String):String{
			return parseProfileImageUrl(profileImageUrl,30);
		}

		//取50*50大小的图片
		public static function getProfileImage50(profileImageUrl:String):String{
			return parseProfileImageUrl(profileImageUrl,50);
		}

		//取180*180的头像
		public static function getProfileImage180(profileImageUrl:String):String{
			return parseProfileImageUrl(profileImageUrl,180);
		}
		
		//加载样式表
		public static function loadStyleDeclarations(styleSwf:String):void{
			StyleManager.loadStyleDeclarations(styleSwf);
		}
		
		//设置容器背景色
		public static function setAsNewMessage(container:Container):void{
			container.setStyle("backgroundAlpha",0.8);
			container.setStyle("backgroundColor",UNREAD_COLOR);
		}
		//是否为新消息背景色
		public static function isUnReadColor(color:uint):Boolean{
			return color == UNREAD_COLOR;//绿色
		}
		//设置为已读背景色,直接清空背景样式
		public static function setReadColor(container:Container):void{
			container.clearStyle("backgroundAlpha");
			container.clearStyle("backgroundColor");
		}
		
		public static function popupWindowTween(win:Object):void{
			var p:Point = getScreenCenter(win.nativeWindow);
			var offset:Number = 10;
			win.nativeWindow.x = p.x + offset;
			win.nativeWindow.y = p.y + offset
			win.width -= offset*2;
			win.height -= offset*2;
			
			win.alpha = 0.2;
			//窗口弹出的缓动效果
			TweenLite.to(win.nativeWindow,1,
					{ease:Elastic.easeOut,
					x:p.x,y:p.y,
					width:win.width+offset*2,height:win.height+offset*2});
			TweenLite.to(win,1,{alpha:1,overwrite:3});//overwrite=3表示和上一效果并行
		}
		
		//弹出视图
		public static function popupView(view:DisplayObject,newx:Number,newy:Number):void{
			var offset:Number = 10;
			//窗口弹出的缓动效果
			view.alpha = 0;
			TweenLite.to(view,0.5,
					{ease:Elastic.easeOut,x:newx-offset,y:newy-offset,alpha:1});
		}
		
		public static function insertText(ta:TextArea,text:String):void{
			var startIndex:int = ta.selectionBeginIndex;
			var endIndex:int = ta.selectionEndIndex;
			var s:String = ta.text;
			s = s.substring(0,startIndex)+"["+text+"]"+s.substr(endIndex);
			ta.text = s;
			ta.selectionBeginIndex = ta.selectionEndIndex = startIndex+text.length+2;
			ta.setFocus();
		}
		
		//产生指定范围内的随机数
		public static function randRange(min:Number, max:Number):Number {
		    var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
		    return randomNum;
		}		
		
		//振动窗口
		public static function shakeWindow(win:Object):void{
			//振动窗口
			var xo:Number = win.nativeWindow.x;
			var yo:Number = win.nativeWindow.y;
			for (var i:int = 0 ;i<6;i++){
				var step:Number = randRange(-8,8);
				var xnew:Number = xo + step;
				var ynew:Number = yo + step;
				TweenLite.to(win.nativeWindow,0.2,{x:xnew,y:ynew,overwrite:0});
			}
		}
		
		//模糊效果
		public static function blur(displayObject:DisplayObject,blurSize:Number = 5):void{
			var blurFilter:BlurFilter = new BlurFilter(blurSize, blurSize, BitmapFilterQuality.HIGH);
			displayObject.filters = [blurFilter];
		}
		
		//获得更让偏离位置
		public static function getOffset(source:DisplayObject,container:Container):Point{
			var p:Point = new Point();
			var r:Rectangle = source.getRect(container);
			p.x = r.x;
			p.y = r.y;
			return p;
		}
		
		//获取指定文件的扩展名，文件是以绝对路径名称存在的
		public static function getFileName(url:String):String{
			var idx:int = url.lastIndexOf("/");
			if(idx!=-1){
				return url.substr(idx+1);
			}
			return null;
		}
		
		//获取短链接链表
		public static function getShortUrlList(str:String):Array{
			var shortUrlRegx:RegExp = /((http[s]?|ftp)?:\/\/(([\w-]+:)?[\w-]+@)?([\w-]+\.)+[\w-]+(:[\d]+)?(\/[\w-   .\/?%&=]*)?(#[\w,]+)?)/gi;
			var ary:Array = str.match(shortUrlRegx);
			return ary;
		}
		
		//加载本地文本文件，并返回文件内容
		public static function loadText(url:String):String{
	        var fUpdate:File = new File(url);
			if(fUpdate.exists){
				var stream:FileStream = new FileStream();    //创建FileStream对象  
				stream.open(fUpdate,FileMode.READ);    //使用FileStream对象以只读方式打开File对象  
				//将文件中的所有信息显示在文本区域中  
				var tmp:String = stream.readMultiByte(stream.bytesAvailable,"UTF-8");
				var lines:Array = tmp.split(LF);
				var s:String = "";
				for each(var line:String in lines){
					s += line;
				}
				stream.close();    //关闭FileStream对象  
				return s;
			}
			return null;	
		}
		
		public static function addMask(container:Container,target:DisplayObject):void{
			var cavMask:Canvas = new Canvas();
			cavMask.visible = cavMask.includeInLayout = false;
			cavMask.width = target.width;
			cavMask.height = target.height;
			cavMask.x = target.x;
			cavMask.y = target.y;
			
			var g:Graphics = cavMask.graphics;
			g.lineStyle(1);
			g.beginFill(0xFFFFFF);
			g.drawRoundRect(0,0,target.width,target.height,8,8);
			g.endFill();
			container.addChild(cavMask);
			
			target.mask = cavMask;
		}
		
		//画虚线
		public static function drawLine(cav:Canvas,yOffset:Number=0,color:uint=0xCCCCCC):void{
			var g:Graphics = cav.graphics;
			g.clear();
			g.lineStyle(0,color);
			for (var i:int =1;i<cav.width+30;i++){
				g.moveTo((i-1)*6+2,yOffset);
				g.lineTo((i-1)*6+6,yOffset);
			}
		}		
		
		/** 表情XML结构
		public function result(data:Object):void{
			xml = "";
			var list:ArrayCollection = data.result.div.ul.li;
			var end:int = txtName.text.indexOf(".");
			var type:String = txtName.text.substr(0,end);
			for each(var item:Object in list){
				var title:String = item.title;
				var name:String = "";
				var src:String = item.a.img.src;
				var idx:int = src.lastIndexOf("/");
				if(idx!=-1){
					name = src.substr(idx+1);
				}
				xml += tab()+"<face>"+"\n";
				xml += tab()+tab()+"<name>"+name+"</name>"+"\n";
				xml += tab()+tab()+"<desc>"+title+"</desc>"+"\n";
				xml += tab()+tab()+"<type>"+type+"</type>"+"\n";
				xml += tab()+"</face>\n";
			}
			txtXML.text = xml;
		} */		
	}
}